import logging
import os, pdb, django, json
import time
import hashlib

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
django.setup()
from django.http import JsonResponse, HttpResponse, StreamingHttpResponse, FileResponse

from conf.sysConfig import config
from user.dataCheck import DataCheck
from user.models import FileStore
# from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client, get_tracker_conf

datacheck = DataCheck()
tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
fileDir = os.path.join(config["dataDir"], config["file"])
coverDir = os.path.join(config["dataDir"], config["cover"])
logoDir = os.path.join(config["dataDir"], config["logo"])
materialDir = os.path.join(config["dataDir"], config["material"])
verificationDir = os.path.join(config["dataDir"], config["verification"])
QAFileDir = os.path.join(config["dataDir"], config["questionAnswer"])
logger_request = logging.getLogger("django.request")
ifUseFastDFS = config["isUseFastDFS"]


def download(fileName, Filetype, filePath, id=''):
    isValid = True
    if ifUseFastDFS:
        isExist = True
    else:
        # 是否存在
        isExist = file_list(fileName, Filetype, filePath)
    if isExist:
        if ifUseFastDFS:
            if Filetype in ["tmpFile"]:
                # if Filetype in ["tmpFile", "QAFile"]:
                msg = 'api/file/fileType=' + Filetype + '/fileName=' + fileName + '/filePath=' + json.dumps(
                    filePath) + '/token=' + getLocalToken(
                    Filetype) + '/'
                return isValid, msg
            else:
                if id != '':
                    fList = FileStore.objects.filter(pk=id)
                else:
                    fList = FileStore.objects.filter(filePath=filePath)
                f = fList[0]
                msg = f.dfsPath
                # msg = 'api/file/fileType=' + Filetype + '/fileName=' + fileName + "/uniqueFile=" + f.uniqueFile + '/token=' + getLocalToken(
                #     Filetype) + '/'
                return isValid, msg
        else:
            # if Filetype in ["tmpFile"]:
            if Filetype in ["tmpFile", "QAFile"]:
                msg = 'api/file/fileType=' + Filetype + '/fileName=' + fileName + '/filePath=' + json.dumps(
                    filePath) + '/token=' + getLocalToken(
                    Filetype) + '/'
                return isValid, msg
            else:
                fList = FileStore.objects.filter(filePath=filePath)
                f = fList[0]
                msg = 'api/file/fileType=' + Filetype + '/fileName=' + fileName + "/uniqueFile=" + f.uniqueFile + '/token=' + getLocalToken(
                    Filetype) + '/'
                return isValid, msg
    else:
        isValid = False
        msg = 'File Not Exist'
        return isValid, msg


class FastDFSStorage():
    def __init__(self, base_url=None, client_conf=None):
        if client_conf is None:
            FastDFS_config = config['FastDFS_config']
            tracker_path = get_tracker_conf(FastDFS_config)
            self.client = Fdfs_client(tracker_path)

    def _save(self, filePath):
        ret = self.client.upload_by_filename(filePath)
        # ret = client.upload_by_filename('/home/ckgit/server/requirements.txt')
        if ret.get("Status") != "Upload successed.":
            return False, ""
        fileName = ret.get('Remote file_id').decode()
        size = ret.get('Uploaded size')
        return True, fileName

    def url(self, name):
        pass


# '/file/<filename>', methods=['GET'])
def file_download_django(request, fileType, fileName, filePath, token):
    if token == getLocalToken(fileType):
        def send_chunk(dir):  # 流式读取
            store_path = json.loads(filePath)
            with open(store_path, 'rb') as target_file:
                while True:
                    chunk = target_file.read(20 * 1024 * 1024)
                    if not chunk:
                        break
                    yield chunk

        # 发送压缩包
        if fileType == 'file':
            choiceDir = fileDir
        elif fileType == 'cover':
            choiceDir = coverDir
        elif fileType == 'logo':
            choiceDir = logoDir
        elif fileType == 'material':
            choiceDir = materialDir
        elif fileType == 'verification':
            choiceDir = verificationDir
        elif fileType == 'QAFile':
            choiceDir = QAFileDir
        else:
            choiceDir = tmpDir
        # infix, back = fileName.split('.')
        response = StreamingHttpResponse(send_chunk(choiceDir))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(fileName).encode('utf-8')
        return response
    else:
        data = {
            'code': 1,
            'success': 'error'
        }
        return JsonResponse(data)


# '/file/<filename>', methods=['GET'])
def file_download_django1(request, fileType, fileName, uniqueFile, token):
    fList = FileStore.objects.filter(uniqueFile=uniqueFile)
    if fList.exists():
        f = fList[0]
        if token == getLocalToken(fileType):
            def send_chunk(dir):  # 流式读取
                store_path = f.filePath
                with open(store_path, 'rb') as target_file:
                    while True:
                        chunk = target_file.read(20 * 1024 * 1024)
                        if not chunk:
                            break
                        yield chunk

            # 发送压缩包
            if fileType == 'file':
                choiceDir = fileDir
            elif fileType == 'cover':
                choiceDir = coverDir
            elif fileType == 'logo':
                choiceDir = logoDir
            elif fileType == 'material':
                choiceDir = materialDir
            elif fileType == 'verification':
                choiceDir = verificationDir
            elif fileType == 'QAFile':
                choiceDir = QAFileDir
            else:
                choiceDir = tmpDir
            # infix, back = fileName.split('.')
            response = StreamingHttpResponse(send_chunk(choiceDir))
            response['Content-Type'] = 'application/octet-stream'
            response['Content-Disposition'] = 'attachment;filename="{0}"'.format(fileName).encode('utf-8')
            return response
        else:
            data = {
                'code': 1,
                'success': 'error'
            }
            return JsonResponse(data)
    else:
        data = {
            'code': 1,
            'success': 'error'
        }
        return JsonResponse(data)


# '/file/<filename>', methods=['GET'])
# async def file_download_nginx(request, fileName):
#    # @restapi.bp.route('/sfile/<name:[A-Za-z0-9/._]+>', methods=["GET"])
#    response = HttpResponse()
# r = json({"status": 0})
# response.headers['Content-Type'] = 'application/pdf'  # 文件类型
#    response['X-Accel-Redirect'] = f'/file/{fileName}'  # 重定向
#    return response


def file_list(fileName, fileType, filePath):
    # files = os.listdir(tmpDir)  # 获取文件目录
    # files = map(lambda x: x if isinstance(x, str) else x.decode('utf-8'), files)  # 注意编码
    # if fileType == 'file':
    #     path = os.path.join(filePath)
    # elif fileType == 'cover':
    #     path = os.path.join(filePath)
    # elif fileType == 'logo':
    #     path = os.path.join(filePath)
    # elif fileType == 'material':
    #     path = os.path.join(filePath)
    # elif fileType == 'verification':
    #     path = os.path.join(filePath)
    # else:
    #     path = ''
    if os.path.exists(filePath):
        return True
    else:
        # pdb.set_trace()
        return False


def getLocalToken(fileType):
    timeStamp = time.time()
    localTime = time.localtime(timeStamp)
    strTime = time.strftime("%Y%m%d%H", localTime)
    str = strTime + fileType
    hl = hashlib.md5()
    hl.update(str.encode(encoding='utf-8'))
    return hl.hexdigest()[0:20]


if __name__ == '__main__':
    # a = download("1.txt", "file", filePath='E:/softwareOnline2/data/software/file/1.txt')[1]
    # print(a)
    fd = FastDFSStorage()
    print(fd._save("C:\\Users\\admin\\Downloads\\202012141958476iEZsgLX.jpg"))
